<template>
  <div class="foot">
    <div class="my-div">
      <a-form :model="params" name="basic" :label-col="{ span: 10 }">
        <a-row>
          <a-col :span="6">
            <a-form-item label="井名" name="wellId" :rules="[{ required: true, message: '请输入井名' }]">
              <a-input v-model:value="params.wellId" style="width: 200px" placeholder="请输入井名" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="油气田" name="gasName">
              <a-input v-model:value="params.gasName" style="width: 200px" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="区域" name="region">
              <a-input v-model:value="params.region" style="width: 200px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="井型" name="wellType">
              <a-select v-model:value="params.wellType" style="width: 200px">
                <a-select-option v-for="item of wellType" :value="item.value" :key="item.value"
                  :label="item.label"></a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="井别" name="wellCategory">
              <a-select v-model:value="params.wellCategory" style="width: 200px">
                <a-select-option v-for="item of wellCategory" :value="item" :key="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="钻井队号" name="teamNumber">
              <a-input v-model:value="params.teamNumber" style="width: 200px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="钻头尺寸(mm)" name="bitSize" :rules="[{ required: true, message: '请输入钻头尺寸' }]">
              <a-select v-model:value="params.bitSize" style="width: 200px">
                <a-select-option v-for="item of bitSize" :value="item" :key="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="作业井深(m)" name="operatingWellDepth">
              <a-input-number v-model:value="params.operatingWellDepth" style="width: 200px" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="最大井斜(°)" name="maxDeviation">
              <a-input v-model:value="params.maxDeviation" style="width: 200px" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="钻井液类型" name="fluidType">
              <a-select v-model:value="params.fluidType" style="width: 200px">
                <a-select-option v-for="item of fluidType" :value="item" :key="item">
                  {{ item }}</a-select-option></a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="钻井液密度(g/cm^3)" name="fluidDensity">
              <a-input v-model:value="params.fluidDensity" style="width: 200px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="钻井液粘度(s)" name="viscosity">
              <a-input v-model:value="params.viscosity" style="width: 200px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="项目部" name="projectDepartment">
              <dept-select-tree :deptId="params.projectDepartment" @confirm="getProjDept"></dept-select-tree>
              <!-- <a-select v-model:value="params.projectDepartment" style="width: 200px">
                <a-select-option v-for="item of projectDepartment" :value="item" :key="item">{{ item }}</a-select-option>
              </a-select> -->
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="施工队伍" name="constructionTeam">
              <!-- <team-select-tree></team-select-tree> -->
              <a-input v-model:value="params.constructionTeam" style="width: 200px"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="作业类别" name="jobClass">
              <a-select v-model:value="params.jobClass" style="width: 200px">
                <a-select-option v-for="item of jobClass" :value="item" :key="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="施工工艺" name="craft">
              <a-select v-model:value="params.craft" style="width: 200px">
                <a-select-option v-for="item of craft" :value="item" :key="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="电缆信息" name="cable">
              <a-button style="width: 200px" @click="openToolModal('cable')">{{ buttonCable }}</a-button>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="弱点设置(lbs)" name="weaknessSettings">
              <a-select v-model:value="params.weaknessSettings" style="width: 200px" allowClear>
                <a-select-option v-for="item of weakRatio" :value="`${item} +/- 3%`" :key="item">
                  {{ `${item} +/- 3% 磅` }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row>
          <!-- <a-col :span="6">
            <a-form-item label="套管程序" name="casing">
              <a-button style="width: 200px" @click="openToolModal('casing')">{{ buttonCasing }}</a-button>
            </a-form-item>
          </a-col> -->
          <a-col :push="2" :span="20">
            <a-space v-for="(casing, index) in dynamicValidateForm.casings" :key="casing.id"
              style="display: flex; margin-left: -400px" align="baseline">
              <a-form-item label="套管程序" :name="['casings', index, 'depth']">
                <a-input-group style="width: 1000px" compact>
                  <!-- <a-button style="width: 200px" @click="openToolModal('casing')">{{ buttonCasing }}</a-button> -->
                  <a-input-number v-model:value="casing.outerDiameter" class="site-input-right"
                    style="width: 200px; text-align: center" placeholder="外径(mm)" :min="0" addon-after="mm" />
                  <a-input v-model:value="value13" class="site-input-split" style="width: 30px; pointer-events: none"
                    placeholder="~" disabled />
                  <a-input style="width: 200px;" v-model:value="casing.deep" placeholder="请输入套管深度范围"></a-input>
                  <!-- <a-input-number v-model:value="casing.deep" class="site-input-right"
                    style="width: 150px; text-align: center" placeholder="深度(m)" :min="0" addon-after="m" /> -->
                </a-input-group>
              </a-form-item>
              <a-form-item>
                <a-button style="margin-left: -150px; width: 200px" v-if="dynamicValidateForm.casings.length > 1"
                  class="dynamic-delete-button" :disabled="dynamicValidateForm.casings.length === 1" type="dashed" block
                  @click="removeCasings(casing)">
                  <MinusCircleOutlined />删除行
                </a-button>
              </a-form-item>
            </a-space>
          </a-col>
        </a-row>
        <a-button type="dashed" style="width: 100%" block @click="addDomain()">
          <PlusOutlined />添加套管程序
        </a-button>
        <a-divider orientation="left">基础信息</a-divider>
        <a-row>
          <a-col :span="6">
            <a-form-item label="复杂类型" name="complexType">
              <a-select v-model:value="params.complexType" style="width: 200px">
                <a-select-option v-for="item of complexType" :value="item" :key="item">{{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="仪器串信息" name="combination" :rules="[{ required: true, message: '请选择仪器串信息' }]">
              <a-button style="width: 200px" @click="openToolModal('combination')">{{ buttonCombination }}</a-button>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="仪器原值" name="instrumentOriginalValue">
              <a-select style="width: 200px" v-model:value="params.instrumentOriginalValue">
                <a-select-option v-for="item of instrumentOriginalValue" :value="item" :key="item">
                  {{ item }}</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="鱼头位置(m)" name="headPosition">
              <a-input-number style="width: 200px" v-model:value="params.headPosition" :min="0" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="落鱼信息" name="fishInformation">
              <a-input v-model:value="params.fishInformation" style="width: 200px" />
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item label="放射源信息" name="radioactiveSourceInformation">
              <a-select style="width: 200px" v-model:value="params.radioactiveSourceInformation" mode="multiple">
                <a-select-option v-for="item of radioactiveSource" :value="item.value" :key="item.value"
                  :label="item.label"></a-select-option>
              </a-select>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>

      <!-- 套管选择弹窗 -->
      <AntdConfirmModal title="套管选择" ref="casingModalRef" width="700px" :keepSlot="false" @confirm="addCasing()">
        <casing-popup-page></casing-popup-page>
      </AntdConfirmModal>
      <!-- 电缆选择弹窗 -->
      <AntdConfirmModal title="电缆选择" ref="cableModalRef" width="1000px" :keepSlot="false" @confirm="addCable">
        <cable-popup-page></cable-popup-page>
      </AntdConfirmModal>
      <!-- 选择仪器串推荐组合弹窗 -->
      <AntdConfirmModal :showConfirm="false" title="仪器串选择" ref="combinationModalRef" width="1200px">
        <instrument-combination-radio @combSuggestSelection="combSuggestSelection"></instrument-combination-radio>
      </AntdConfirmModal>
    </div>
  </div>
  <div class="steps-action">
    <a-button style="margin-left: 8px" type="primary" @click="next">下一步</a-button>
  </div>
</template>
<script setup>
import { MinusCircleOutlined, PlusOutlined, DownOutlined } from "@ant-design/icons-vue";
import { getOne as getCombDetail, queryOne as getOneComb } from "@/api/tool/combination.js";
import { queryList } from "@/api/salvage/threadCard.js";
import { queryOne } from "@/api/tool/cable.js";
import { wellType, wellCategory, craft, complexType, bitSize, radioactiveSource, jobClass, instrumentOriginalValue, fluidType, weakRatio, projectDepartment } from '@/custom/salvage/constant/report.js'
import DeptSelectTree from "@/custom/salvage/components/DeptSelectTree.vue";
import TeamSelectTree from "@/custom/salvage/components/TeamSelectTree.vue";
import CasingPopupPage from '@/custom/well/components/CasingPopupPage.vue';
import CablePopupPage from '@/custom/well/components/CablePopupPage'
import InstrumentCombinationRadio from "@/custom/preTest/pages/plan/components/instrument/type/CombRadio.vue";
import useApp from "@/hooks";
const { $, proxy } = useApp();
const emit = defineEmits(["getCurrent"]);
const props = defineProps({
  reportQuery: {
    type: Object,
  },
  state: {
    type: String,
  },
  schemesData: {
    type: Object,
  }
});
const query = ref({ pageNum: 1, pageSize: 10, sortBy: 'id', searchKey: '' });
const dynamicValidateForm = reactive({
  casings: [],
});
const params = reactive({
  wellId: '',
  gasName: "",
  region: "",
  wellCategory: "",
  wellType: "",
  teamNumber: "",
  complexType: "",
  operatingWellDepth: "",
  maxDeviation: "",
  bitSize: "",
  cableId: '',
  combinationId: '',
  jobClass: '',
  headPosition: '',
  fishInformation: '',
  casingList: [],
  fluidDensity: '',
  viscosity: '',
  fluidType: '',
  projectDepartment: '',
  constructionTeam: '',
  craft: '',
  // instrumentStringFileId: '',
  instrumentOriginalValue: '',
  radioactiveSourceInformation: [],
  weaknessSettings: '',
});
const buttonCasing = ref("选择套管");
const buttonCable = ref("选择电缆");
const buttonCombination = ref("选择仪器串");
const casingModalRef = ref(null);
const cableModalRef = ref(null);
const combinationModalRef = ref(null);
// const combSuggesQuery = ref({}); //仪器串相关信息

// 打开工具弹窗
function openToolModal(e) {
  console.log('openToolModal', e);
  if (e == 'casing') {
    casingModalRef.value.openModal()
  } else if (e == 'cable') {
    cableModalRef.value.openModal()
  } else if (e == 'combination') {
    combinationModalRef.value.openModal()
  }
}

function setNewData(res) {
  dynamicValidateForm.casings = []
  for (const key in res) {
    if (res.hasOwnProperty(key) && params.hasOwnProperty(key)) {
      params[key] = res[key]; // 共有属性赋值赋值
    }
  }
  let casingStart = 0
  res.casingList?.forEach((e) => {
    dynamicValidateForm.casings.push({
      outerDiameter: e.outerDiameter,
      start: casingStart,
      deep: e.deep,
      name: e.name,
      id: e.deep,
    });
    casingStart = e.deep
  });
  showCable(res?.cableId)
  showCombination(res?.combinationId)
}

function getReportQuery() {
  let state = localStorage.getItem("state");
  if (state === "修改" && Object.keys(props.reportQuery).length === 0) {
    console.log('getReportQuery修改', props.schemesData);
    setNewData(props.schemesData);
  } else if (state === "补充") {
    // 测前方案的相同井信息赋值
    console.log('props.schemesData', props.schemesData)
    params.wellId = props.schemesData.wellId
    params.wellCategory = props.schemesData.wellCategory
    params.wellType = props.schemesData.wellType
    params.drillingNumber = props.schemesData.drillingUnit
    params.maxDeviation = props.schemesData.maximumInclination
    // params.instrumentStringFileId = props.schemesData.stringFileId
    params.weaknessSettings = props.schemesData.f_break_tensile_rod_range
    // 查询收集卡列表是否存在该井
    queryList(query.value).then(res => {
      const foundObj = res.content.find(obj => {
        if (obj.wellId === params.wellId) {
          return true; // 如果找到满足条件的对象，则返回 true
        }
      });
      if (foundObj) {
        console.log(`找到满足条件的对象:`, foundObj);
        params.cableId = foundObj.cableId
        params.combinationId = foundObj.combinationId
        showCable(params.cableId)
        showCombination(params.combinationId)
      }
    })
    setNewData(props.reportQuery);
  } else if (state === "新建") {
    setNewData(props.reportQuery);
  } else {
    setNewData(props.reportQuery);
  }
}
getReportQuery()
// 部门信息
function getProjDept(e) {
  // console.log('项目部', e);
  params.projectDepartment = e
}
// 添加一个套管
const addDomain = () => {
  dynamicValidateForm.casings.push({
    outerDiameter: null,
    deep: null,
    name: `套管${dynamicValidateForm.casings.length + 1}`,
    id: Date.now(),
  });
};
// 移出一个套管
const removeCasings = (item) => {
  let index = dynamicValidateForm.casings.indexOf(item);
  if (index !== -1) {
    dynamicValidateForm.casings.splice(index, 1);
  }
};
// 添加仪器串组合推荐
function combSuggestSelection(item) {
  console.log('combSuggestSelectio', item);
  // params.instrumentStringFileId = item.combinationFileId
  params.combinationId = item.id
  // params.instrumentName = item.combinationName
  // //查询仪器串包含的仪器所有信息
  // getCombDetail(item.id).then((res) => {
  //   console.log(res);
  //   combSuggesQuery.value.instrumentIdList = [];
  //   combSuggesQuery.value.totalLength = 0;
  //   combSuggesQuery.value.maxOuterDiameter = 0;
  //   combSuggesQuery.value.totalWeight = 0;
  //   // 查找是否含有马笼头
  //   res.forEach((e) => {
  //     // 如果有，将马笼头仪器参数名称与其他仪器参数名称统一
  //     if (e.hasOwnProperty("horseheadId")) {
  //       e.instrumentId = e.horseheadId;
  //       e.outerDiameter = e.maxDiameter;
  //       e.instrumentName = e.horseheadName;
  //       e.weight = 0;
  //     }
  //     //为新建仪器串推荐负载参数赋值
  //     combSuggesQuery.value.maxOuterDiameter =
  //       combSuggesQuery.value.maxOuterDiameter > e.outerDiameter ? combSuggesQuery.value.maxOuterDiameter : e.outerDiameter;
  //     combSuggesQuery.value.totalLength = combSuggesQuery.value.totalLength + e.length;
  //     combSuggesQuery.value.totalWeight = combSuggesQuery.value.totalWeight + e.weight;
  //     combSuggesQuery.value.instrumentIdList.push(e.id);
  //   });
  //   combSuggesQuery.value.instrumentCombination = item.instrumentNameList;
  //   combSuggesQuery.value.totalWeight = combSuggesQuery.value.totalWeight.toFixed(2);
  //   combSuggesQuery.value.totalLength = combSuggesQuery.value.totalLength.toFixed(2);
  //   // combSuggesQuery.value.schemeId = localStorage.getItem("schemeId");
  // });
  showCombination(item.id)
  combinationModalRef.value.closeModal();
}
// 添加电缆信息
function addCable() {
  let cableData = JSON.parse(localStorage.getItem('selectCables'))
  console.log('cableData', cableData);
  params.cableId = cableData[0].id
  showCable(cableData[0].id)
  cableModalRef.value.closeModal();
}
// 电缆信息展示
function showCable(id) {
  if (id) {
    queryOne(id).then(res => {
      console.log(res);
      buttonCable.value = `已选择${res.diameter}mm的电缆`
    })
  } else {
    buttonCable.value = "选择电缆"
  }
}
// 仪器串信息展示
function showCombination(id) {
  if (id) {
    getOneComb(id).then(res => {
      console.log(res);
      buttonCombination.value = `已选择${res.combinationName}`
    })
  } else {
    buttonCombination.value = "选择仪器串"
  }
}
// 添加套管信息
function addCasing() {
  let casingData = JSON.parse(localStorage.getItem('selectCasing'))
  console.log('casingData', casingData);
  buttonCasing.value = `已选择${casingData[0].outerDiameter}mm的套管`
  casingModalRef.value.closeModal();
}
// 下一步
function next() {
  params.casingList = dynamicValidateForm.casings;
  if (params.wellId == '') { $.showToast({ title: '井名不允许为空', icon: 'warn' }) }
  else if (!params.cableId) { $.showToast({ title: '请选择电缆', icon: 'warn' }) }
  else if (!params.combinationId) { $.showToast({ title: '请选择仪器串', icon: 'warn' }) }
  else if (params.bitSize == 0) { $.showToast({ title: '请输入钻头尺寸', icon: 'warn' }) }
  else if (params.casingList.length == 0 ||
    params.casingList[params.casingList.length - 1].outerDiameter == null ||
    params.casingList[params.casingList.length - 1].deep == null) {
    $.showToast({
      title: '套管数据不允许为空',
      icon: 'warn'
    })
  } else {
    params.page = 1;
    console.log('下一步', params);
    emit("getCurrent", params);
  }
}
</script>

<style scoped>
.steps-action {
  margin-top: 24px;
}

.my-div {
  width: 1370px;
  padding: 10px;
  transform: scaleY(-1);
}

.foot {
  overflow-x: auto;
  transform: scaleY(-1);
}

.centered-menu-item {
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>